/***************************************************************************
 *   KShootout - online shootout card game.                                *
 *   Copyright (C) 2008, 2009  MacJariel                                   *
 *                                                                         *
 *   KShootout is free software: you can redistribute it and/or modify     *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   KShootout is distributed in the hope that it will be useful,          *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with KShootout.  If not, see <http://www.gnu.org/licenses/>.    *
 ***************************************************************************/
#include "util.h"
#include <cstdlib>
#include <ctime>

#ifdef Q_OS_UNIX
    #include <csignal>
#endif

void randomize()
{
    time_t seed;
    time(&seed);
    qsrand((uint) seed);
}

void setSignalHandlers()
{
    #ifdef Q_OS_UNIX
        // ignore broken-pipe signal eventually caused by sockets
        signal(SIGPIPE, SIG_IGN);
    #endif
}

QString randomToken(int minLength, int maxLength)
{
    Q_ASSERT(minLength <= maxLength);
    const static char* chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    const static int charl = strlen(chars);
    int length = minLength + ((int)qrand() % (maxLength - minLength + 1));
    char token[length+1];
    for (int i = 0; i < length; ++i)
    {
        token[i] = chars[qrand() % charl];
    }
    token[length - 1] = '\0';
    return QString(token);
}

bool randomBool(qreal probability)
{
    int random_val_size = 4096;
    int true_val_treshold = (int)(random_val_size * probability);
    int random_val = qrand() % random_val_size;
    return (random_val < true_val_treshold);
}

QString boolToString(bool aBool)
{
    return aBool ? "true" : "false";
}

bool stringToBool(QString aString)
{
    aString = aString.toLower();
    if (aString == "true" || aString == "1") return 1;
    return 0;
}
